package com.components.zxing.scan.decoding

import android.app.Activity
import java.util.concurrent.*

/**
 * @Author LuoKun
 * @Des
 */
class InactivityTimer(private var activity: Activity) {

    companion object {
        private const val INACTIVITY_DELAY_SECONDS = 5 * 60

        private class DaemonThreadFactory : ThreadFactory {
            override fun newThread(runnable: Runnable): Thread {
                val thread = Thread(runnable)
                thread.isDaemon = true
                return thread
            }
        }
    }

    private var inactivityTimer: ScheduledExecutorService?=null
    private var inactivityFuture: ScheduledFuture<*>? = null

    init {
        inactivityTimer = Executors.newSingleThreadScheduledExecutor(
            DaemonThreadFactory()
        )
        onActivity()
    }

    fun onActivity() {
        cancel()
        inactivityFuture = inactivityTimer?.schedule(
            FinishListener(activity),
            INACTIVITY_DELAY_SECONDS.toLong(),
            TimeUnit.SECONDS
        )
    }

    private fun cancel() {
        if (inactivityFuture != null) {
            inactivityFuture!!.cancel(true)
            inactivityFuture = null
        }
    }

    fun shutdown() {
        cancel()
        inactivityTimer?.shutdown()
    }

}